import logging
import os
import time
from frame_work.setting import log_Path


class Logger(object):
    def __init__(self, logger):
        '''''
            指定保存日志的文件路径，日志级别，以及调用文件
            将日志存入到指定的文件中
        '''

        # 创建一个logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)

        # 日志路径
        rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        name = rq + '.log'
        log_Name = os.path.join(log_Path, name)

        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler(log_Name, encoding='utf-8')
        # fh.setLevel(logging.INFO)

        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        # ch.setLevel(logging.INFO)

        # 定义handler的输出格式
        formatter_fh = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(filename)s[:%(lineno)d]- %(message)s')
        formatter_ch = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter_fh)
        ch.setFormatter(formatter_ch)

        # 给logger添加handler
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

        # 过滤级别：控制台输出INFO以上级别，文件只记录DEBUG级别
        info_filter = logging.Filter()
        info_filter.filter = lambda record: record.levelno >= logging.INFO  # 控制台设置过滤等级
        err_filter = logging.Filter()
        err_filter.filter = lambda record: record.levelno < logging.INFO  # 文件日志设置过滤级别

        ch.addFilter(info_filter)
        # fh.addFilter(err_filter)

    def get_logger(self):
        return self.logger
